jQuery(document).ready(function($) {

   var logoheight = 180, logowidth = 180; 

   if(!(window.XMLHttpRequestUpload && window.FileReader)) {
      $('#uploadlogoform .file_upload_label').html($('#uploadlogoform .file_upload_label').data('nodragtext'));
   }

   $("#uploadlogoform input[type='file']").val('');

   $('#uploadlogoform').fileUploadUIX({
      allowImageType: true, 
      keepList: true,
      autoUpload: true, 
      maxFileSize: 4*1024*1024,
      onCompleteAll: function(list) {
         // cancel previous binding 
         $("#imagecontainer img").imgAreaSelect({remove:true});

         // get logo again 
         getCurrentImageSelection(function(data) { setImageSelection(data); }); 

      }
   }).css("visibility", "visible"); 

   function getOrigScale() {

      var currentimg = $("#imagecontainer img");
      var imgwidth = $(currentimg).width();
      var imgheight = $(currentimg).height();
      var data = currentimg.data();

      var origwidth = data && data.image_x ? data.image_x : imgwidth; 
      origwidth = origwidth >0 ? origwidth : imgwidth; 
      var origheight = data && data.image_y ? data.image_y : imgheight; 
      origheight = origheight>0 ? origheight : imgheight; 
      // recalculate scale 
      scaleX = origwidth / imgwidth; 
      scaleY = origheight / imgheight;
      return {scaleX: scaleX, scaleY: scaleY}
   }

   function preview(currentimg, selection) { 
      var imgwidth = $(currentimg).width();
      var imgheight = $(currentimg).height();

      if(selection.width ==0 || selection.height == 0)
         return; 

      $('#logopreview img').each(function() {
         var viewwidth = parseInt($(this).parent().css("width")); 
         var viewheight = parseInt($(this).parent().css("height"));
         var scaleX  = viewwidth / selection.width; 
         var scaleY =  viewheight / selection.height;

         var width = Math.round(scaleX * imgwidth);  
         $(this).css({ 
            width: width + 'px', 
            height: Math.round(scaleY * imgheight) + 'px',
            marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
            marginTop: '-' + Math.round(scaleY * selection.y1) + 'px',
            maxWidth: (imgwidth > width ? imgwidth : width) + 'px'
         });
      });

      /* recalculate original scale */
      var oscale = getOrigScale();
      scaleX = oscale.scaleX;
      scaleY = oscale.scaleY;
      /* get original image width/height */
      $('#logopreview #x1').val(selection.x1 * scaleX);
      $('#logopreview #y1').val(selection.y1 * scaleY);
      $('#logopreview #x2').val(selection.x2 * scaleX);
      $('#logopreview #y2').val(selection.y2 * scaleY);
   } 


   $('#logopreview #thumbnailform').ajaxForm({
         dataType: "json", 
         beforeSubmit: function(data, form, options) {
            var tx1 = $('#logopreview #x1').val();
            var ty1 = $('#logopreview #y1').val();
            var tx2 = $('#logopreview #x2').val();
            var ty2 = $('#logopreview #y2').val();
            if(tx1=="" || ty1=="" || tx2=="" || ty2=="") {
               showMessageDialog("You must make a selection first");
               return false;
            }
            if(!showLoading(form.closest(".logoshow")))
               return false;
         },
         success: function(data) {
            if(data.error) { showMessageDialog(data.error); }
            else if(data.success) {
               $("#logopreview #error").html(data.success).show().fadeOut(3000);
               /*
               $("#navigation a").filterAttr('data-id','company_index').find('i.hr_i_setting').
                  css('background-image', 'url("' + data.data + '")'). 
                  css('background-position', '0 0'); 
               */
            }
         }
   });

   // initial section 
   function getCurrentImageSelection(callback) {
      $.getJSON(getlogourl, function(data) {
          if(data && data.imageid && callback) {
            var currentimg = $("#imagecontainer img");
            currentimg.attr("src", data.filename+'?_='+$.now()).data(data).show();
            currentimg.one('load', function() {
               $("#logopreview").show();
               var handler = setInterval(function() { 
                  if(currentimg.height() > 1) {
                     clearInterval(handler);
                     callback(data);
                  }
               }, 500); 
            }).each(function() {
               /* if load from browser cache, we have complete property */
               if(this.complete) $(this).load();
            });
          }
      });
   }

   function setImageSelection(data) {
      var x1 = x2 = y1 = y2 = 0;
      if(data.logoimageid && data.x1) {
         x1 = data.x1; x2 = data.x2; y1 = data.y1; y2 = data.y2;
      }

      if(x1 ==0 && x2 ==0 && y1 ==0 && y2 ==0) {
         var imgwidth = data.image_x; 
         var imgheight = data.image_y; 
         x1 = y1 = 0;
         // use logo default width/height for range 
         x2 = logowidth+x1;
         y2 = logoheight+y1; 
      }
      else {
         /* scale back based on current size */
         var oscale = getOrigScale();
         var scaleX = oscale.scaleX;
         var scaleY = oscale.scaleY;
         x1 = x1 / scaleX; 
         x2 = x2 / scaleX; 
         y1 = y1 / scaleY; 
         y2 = y2 / scaleY; 
      }

      var currentimg = $("#imagecontainer img");
      $("#imagecontainer").parent().css("height", "auto"); 
      $('#logopreview img').each(function() { $(this).attr("src", currentimg.attr("src")); })
      $('#logopreview #imageid').val(data.imageid);

      currentimg.imgAreaSelect({ 
           // aspectRatio: '1:'+(logoheight/logowidth),
           x1: x1, y1: y1, x2: x2, y2: y2, 
           onSelectChange: preview 
      });

      preview(currentimg, {x1:x1, x2:x2,y1:y1,y2:y2,width:(x2-x1),height:(y2-y1)});
   }

   $.ajaxSetup({ cache: false });
   /* get last picture of logo */
   getCurrentImageSelection(function(data) { setImageSelection(data); }); 

}); 
